<template>
  <div class="orders-page">
    <header-nav />
    
    <!-- <div class="breadcrumb">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>您的账户</el-breadcrumb-item>
        <el-breadcrumb-item>我的订单</el-breadcrumb-item>
      </el-breadcrumb>
    </div> -->

    <div class="main-content">
      <!-- 统一导航菜单 -->
      <user-nav-menu active-menu="orders" />

      <div class="orders-container">
        <!-- 订单筛选 -->
        <el-card class="filter-card">
          <el-form :inline="true" :model="filterForm">
            <el-form-item label="订单状态">
              <el-select v-model="filterForm.status" placeholder="全部状态">
                <el-option label="全部" value="" />
                <el-option label="待付款" value="pending" />
                <el-option label="已付款" value="paid" />
                <el-option label="已发货" value="shipped" />
                <el-option label="已完成" value="completed" />
                <el-option label="已取消" value="cancelled" />
              </el-select>
            </el-form-item>
            <el-form-item label="下单时间">
              <el-date-picker
                v-model="filterForm.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="resetFilter">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 订单列表 -->
        <div v-if="loading" class="loading">
          <el-skeleton :rows="3" animated />
        </div>
        
        <div v-else-if="orders.length === 0" class="empty-orders">
          <el-empty description="暂无订单">
            <el-button type="primary" @click="$router.push('/')">
              去购物
            </el-button>
          </el-empty>
        </div>
        
        <div v-else class="orders-list">
          <el-card v-for="order in orders" :key="order.id" class="order-card">
            <template #header>
              <div class="order-header">
                <div class="order-info">
                  <span class="order-no">订单号：{{ order.order_no }}</span>
                  <span class="order-date">{{ formatDate(order.created_at) }}</span>
                </div>
                <el-tag :type="getOrderStatusType(order.status)">
                  {{ getOrderStatusText(order.status) }}
                </el-tag>
              </div>
            </template>
            
            <div class="order-items">
              <div v-for="item in order.items" :key="item.id" class="order-item">
                <el-image 
                  :src="getImageUrl(item.image)" 
                  :alt="item.name"
                  class="item-image"
                >
                  <template #error>
                    <div class="image-placeholder">
                      <el-icon><Picture /></el-icon>
                      <p>图片加载失败</p>
                    </div>
                  </template>
                </el-image>
                <div class="item-info">
                  <h4>{{ item.name }}</h4>
                  <p class="item-price">
                    ¥{{ Number(item.price).toFixed(2) }} × {{ item.quantity }}
                  </p>
                </div>
              </div>
            </div>
            
            <div class="order-footer">
              <div class="order-total">
                共 {{ getTotalQuantity(order.items) }} 件商品，
                总计：<span class="total-amount">¥{{ Number(order.total_amount).toFixed(2) }}</span>
              </div>
              <div class="order-actions">
                <el-button 
                  v-if="order.status === 'shipped'"
                  type="success" 
                  size="small"
                  @click="handleConfirmReceive(order)"
                >
                  确认收货
                </el-button>
                <el-button 
                  v-if="order.status === 'pending'"
                  type="danger" 
                  size="small"
                  @click="handleCancel(order)"
                >
                  取消订单
                </el-button>
              </div>
            </div>
          </el-card>
        </div>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[5, 10, 20, 50]"
            :total="total"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import HeaderNav from '../components/HeaderNav.vue'
import UserNavMenu from '../components/UserNavMenu.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from '../utils/axios'

const router = useRouter()
const orders = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)

const filterForm = ref({
  status: '',
  dateRange: []
})

const fetchOrders = async () => {
  try {
    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      status: filterForm.value.status,
      startDate: filterForm.value.dateRange?.[0],
      endDate: filterForm.value.dateRange?.[1]
    }
    
    const { data } = await axios.get('/api/orders', { params })
    console.log('Fetched orders:', data)
    orders.value = data.orders
    total.value = data.total
  } catch (error) {
    console.error('Error:', error)
    ElMessage.error('获取订单列表失败')
  }
}

const handleSearch = () => {
  currentPage.value = 1
  fetchOrders()
}

const resetFilter = () => {
  filterForm.value = {
    status: '',
    dateRange: []
  }
  handleSearch()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchOrders()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchOrders()
}

const handlePay = async (order) => {
  // 实现支付逻辑
  ElMessage.info('支付功能开发中...')
}

const handleConfirmReceive = async (order) => {
  try {
    await ElMessageBox.confirm('确认已收到商品？')
    await axios.post(`/api/orders/${order.id}/confirm`)
    ElMessage.success('确认收货成功')
    fetchOrders()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Error:', error)
      ElMessage.error('操作失败')
    }
  }
}

const handleCancel = async (order) => {
  try {
    await ElMessageBox.confirm('确认取消订单？')
    await axios.post(`/api/orders/${order.id}/cancel`)
    ElMessage.success('订单已取消')
    fetchOrders()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Error:', error)
      ElMessage.error('操作失败')
    }
  }
}

const handleReview = (order) => {
  router.push(`/order/${order.id}/review`)
}

const handleOrderDetail = (order) => {
  router.push(`/order/${order.id}`)
}

const formatDate = (date) => {
  return new Date(date).toLocaleString('zh-CN')
}

const getTotalQuantity = (items) => {
  return items.reduce((sum, item) => sum + item.quantity, 0)
}

const getOrderStatusType = (status) => {
  const types = {
    pending: 'warning',
    paid: 'success',
    shipped: 'primary',
    completed: 'success',
    cancelled: 'info'
  }
  return types[status] || 'info'
}

const getOrderStatusText = (status) => {
  const texts = {
    pending: '待付款',
    paid: '已付款',
    shipped: '已发货',
    completed: '已完成',
    cancelled: '已取消'
  }
  return texts[status] || status
}

// 处理图片URL
const getImageUrl = (image) => {
  if (!image) return '';
  if (image.startsWith('http')) return image;
  return `${import.meta.env.VITE_API_URL}${image}`;
}

onMounted(() => {
  fetchOrders()
})
</script>

<style scoped>
.orders-page {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.main-content {
  max-width: 1400px;
  margin: 60px auto 0;
  padding: 20px;
}

.orders-container {
  background: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.breadcrumb {
  margin: 20px 0;
}

.filter-card {
  margin-bottom: 20px;
}

.order-card {
  margin-bottom: 20px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-info {
  display: flex;
  gap: 20px;
}

.order-no {
  font-weight: bold;
}

.order-date {
  color: #666;
}

.order-items {
  margin: 20px 0;
}

.order-item {
  display: flex;
  gap: 20px;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.order-item:last-child {
  border-bottom: none;
}

.item-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
}

.item-info {
  flex: 1;
}

.item-info h4 {
  margin: 0 0 10px;
}

.item-price {
  color: #666;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.total-amount {
  color: #ff6b6b;
  font-size: 18px;
  font-weight: bold;
}

.order-actions {
  display: flex;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.loading {
  text-align: center;
  padding: 20px;
}

.empty-orders {
  text-align: center;
  padding: 20px;
}

.image-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
}
</style> 